#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""s8.hk api
http://code.google.com/p/s8hk-api/wiki/ApiDocumentation
"""
from urllib import urlencode

from tornado.web import asynchronous, HTTPError
from tornado.httpclient import AsyncHTTPClient
from tornado import escape

from jsonphandler import JSONPHandler

        
class S8ShortenHandler(JSONPHandler):
    @asynchronous
    def get(self):
        url = self.get_argument('longUrl', None)
        if url is None:
            url = self.get_argument('longurl')
        source = self.get_argument('source', 'jsonp')
        heart = self.get_argument('heart', None)
        args = {'longUrl': escape.utf8(url)}
        if source is not None:
            args['source'] = escape.utf8(source)
        if heart is not None:
            args['heart'] = escape.utf8(heart)
        http = AsyncHTTPClient()
        http.fetch("http://s8.hk/api/shorten?%s" % urlencode(args),
                   callback=self.async_callback(self.on_response))

    def on_response(self, response):
        if response.error: 
            raise HTTPError(500)
        self.write(escape.json_encode(response.body))
        self.finish()
        
class S8ExpandHandler(JSONPHandler):
    @asynchronous
    def get(self):
        url = self.get_argument('shortUrl', None)
        if url is None:
            url = self.get_argument('shorturl')
        format = self.get_argument('format', 'json')
        http = AsyncHTTPClient()
        http.fetch("http://s8.hk/api/expand?shortUrl=%s&format=%s" % (escape.url_escape(url), format),
                   callback=self.async_callback(self.on_response))

    def on_response(self, response):
        if response.error: 
            raise HTTPError(500)
        self.write(escape.json_encode(response.body))
        self.finish()